const YDirectionMap = {
    UP: 'UP',
    DOWN: 'DOWN',
} as const;
const XDirectionMap = {
    LEFT: 'LEFT',
    RIGHT: 'RIGHT',
} as const;
export const DirectionMap = {
    ...YDirectionMap,
    ...XDirectionMap
} as const;

export type YDirection = typeof YDirectionMap[keyof typeof YDirectionMap];
export type XDirection = typeof XDirectionMap[keyof typeof XDirectionMap];
export type Direction = YDirection | XDirection;

export const ALLOW_KEYS = ['KeyA', 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'];

export class Keyboard {
    _xDirection: XDirection | undefined;
    _yDirection: YDirection | undefined;
    _pressKey: string | undefined;
    pressKeys: string[] = [];
    pressBlank = false;
    SPEED = 5
    constructor() {
        document.addEventListener("keydown", this.handleKeydown);
        document.addEventListener("keyup", this.handleKeyup);
    }

    handleKeydown = (e: KeyboardEvent) => {
        const code = e.code;
        if (!ALLOW_KEYS.includes(code)) {
            return;
        }
        this._pressKey = e.code;
        this.pressBlank = true;
        if (!this.pressKeys.includes(e.code)) {
            this.pressKeys.push(e.code);
        }
    };

    handleKeyup = (e: KeyboardEvent) => {
        const code = e.code;
        if (!ALLOW_KEYS.includes(code)) {
            return;
        }
        this._pressKey = undefined;
        this.pressBlank = false;
        this.pressKeys = this.pressKeys.filter((code) => code !== e.code);
    };

    get isPressing () {
        return this.pressKeys.length > 0;
    }

    get pressKey () {
        return this._pressKey
    }

}
